//
//  WCAddrEditVC.m
//  CBT
//
//  Created by apple on 2019/7/8.
//  Copyright © 2019 Mr.Zhang. All rights reserved.
//

#import "WCAddrEditVC.h"
#import "WCAddrEditCell.h"
#import "WCAddrSelectCell.h"
//#import "WCAreaPickerView.h"
#import "UserManager.h"

@interface WCAddrEditVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
//@property (nonatomic, strong) WCAreaPickerView *pickView;
//@property (nonatomic, weak) UILabel *AddressLabel;
@property (nonatomic, strong) UIButton *saveBtn;


@property (nonatomic, strong) UITextField *usernameTF;
@property (nonatomic, strong) UITextField *phoneTF;
@property (nonatomic, strong) UITextField *addressTF;
// 省市区
@property (nonatomic, strong) UITextField *provinceTF;


@end

@implementation WCAddrEditVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = kLocalizedString(@"管理收货地址",nil);
    
    [self.view addSubview:self.tableView];
    self.tableView.rowHeight = 48;
    [self.tableView registerClass:[WCAddrEditCell class] forCellReuseIdentifier:@"addreditCell"];
    [self.tableView registerClass:[WCAddrSelectCell class] forCellReuseIdentifier:@"addrselectCell"];
    
    [self.view addSubview:self.saveBtn];
    
}

- (void)addUserAddress {
    @weak(self)
    NSString *phone = self.phoneTF.text;
    NSString *addr = self.addressTF.text;
    NSString *userName = self.usernameTF.text;
    
    if ([NSString isBlankString:userName]) {
        [HFStatusView showFailureMessage:kLocalizedString(@"请输入姓名",nil)];
        return;
    }
    if ([NSString isBlankString:phone]) {
        [HFStatusView showFailureMessage:kLocalizedString(@"请输入手机",nil)];
        return;
    }
    if ([NSString isBlankString:addr]) {
        [HFStatusView showFailureMessage:kLocalizedString(@"请输入地址详情",nil)];
        return;
    }
    
    NSMutableDictionary * param = [[NSMutableDictionary alloc]init];
    [param setObject:[CBTLocalUserManager sharedInstance].userId forKey:@"userId"];
    [param setObject:addr forKey:@"address"];
    [param setObject:userName forKey:@"userName"];
    [param setObject:phone forKey:@"phone"];
    [param setObject:@"" forKey:@"province"];
    [param setObject:@"" forKey:@"city"];
    [param setObject:@"" forKey:@"area"];
    
    [UserManager addUserAddressWithUserId:[CBTLocalUserManager sharedInstance].userId paras:param block:^(id data, HttpRequestResult result, NSString *msg) {
        if (result == kHttpRequestResultNormal) {
            [HFStatusView showFailureMessage:data[@"message"]];
            dispatch_after(1, dispatch_get_main_queue(), ^{
                
                NSDictionary *subDic = data[@"data"];
                if ([subDic[@"code"] intValue] == 100) {
                    [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"address"];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    
                    [self_weak_.navigationController popViewControllerAnimated:YES];
                }
            });
        }
        else {
            [HFStatusView showFailureMessage:kLocalizedString(@"网络异常，请稍后重试", nil)];
        }
    }];
}

- (void)updateUserAddress {
    @weak(self)
    NSString *phone = self.phoneTF.text;
    NSString *addr  = self.addressTF.text;
    NSString *userName = self.usernameTF.text;
    
    phone = [phone stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    if ([NSString isBlankString:userName]) {
        [HFStatusView showFailureMessage:kLocalizedString(@"请输入姓名",nil)];
        return;
    }
    if ([NSString isBlankString:phone]) {
        [HFStatusView showFailureMessage:kLocalizedString(@"请输入手机",nil)];
        return;
    }
    if ([NSString isBlankString:addr]) {
        [HFStatusView showFailureMessage:kLocalizedString(@"请输入地址详情",nil)];
        return;
    }

    NSMutableDictionary *param = [[NSMutableDictionary alloc]init];
    [param setObject:[CBTLocalUserManager sharedInstance].userId forKey:@"userId"];
    [param setObject:addr     forKey:@"address"];
    [param setObject:userName forKey:@"userName"];
    [param setObject:phone    forKey:@"phone"];
    [param setObject:@"" forKey:@"province"];
    [param setObject:@"" forKey:@"city"];
    [param setObject:@"" forKey:@"area"];
    [param setObject:self.addressId forKey:@"id"];

    [UserManager updateUserAddressWithUserId:[CBTLocalUserManager sharedInstance].userId params:param block:^(id data, HttpRequestResult result, NSString *msg) {
        if (result == kHttpRequestResultNormal) {
            [HFStatusView showSuccessMessage:data[@"message"]];
            dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));
            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                [self_weak_.navigationController popViewControllerAnimated:YES];
            });
        }
        else {
            [HFStatusView showFailureMessage:kLocalizedString(@"网络异常，请稍后重试", nil)];
        }
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
//    if (indexPath.row == 2) {
//        WCAddrSelectCell *cell = [WCAddrSelectCell createTableView:tableView];
//        self.AddressLabel = cell.titleNameLabel;
//
//        if (self.userName && self.userName.length) {
//            cell.titleNameLabel.text = [NSString stringWithFormat:@"%@-%@-%@",self.province,self.city,self.area];
//        }
//
//        return cell;
//    }
//    else {
        WCAddrEditCell *cell = [WCAddrEditCell createTableView:tableView];
        NSString *placeholder = @"请输入收款人姓名";
        switch (indexPath.row) {
            case 0:
                placeholder = @"请输入收款人姓名";
                self.usernameTF = cell.textField;
                if (self.userName && self.userName.length) {
                    cell.textField.text = self.userName;
                }
                break;
            case 1:
                placeholder = @"请输入收款人电话";
                cell.textField.keyboardType = UIKeyboardTypePhonePad;
                self.phoneTF = cell.textField;
                if (self.phone && self.phone.length) {
                    cell.textField.text = [self handlePhone:self.phone];
                }
                break;
//            case 2:
//                placeholder = @"请输入省市区";
//                cell.textField.keyboardType = UIKeyboardTypePhonePad;
//                self.provinceTF = cell.textField;
//                if (self.provinceAddress && self.provinceAddress.length) {
//                    cell.textField.text = self.provinceAddress;
//                }
//                break;
            case 2:
                placeholder = @"请输入收货详细地址";
                self.addressTF = cell.textField;
                if (self.address && self.address.length) {
                    cell.textField.text = [NSString stringWithFormat:@"%@%@%@%@",self.province,self.city,self.area,self.address];
                }
            default:
                break;
        }
        cell.textField.placeholder = placeholder;

        return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
//    self.pickView = [[WCAreaPickerView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 400, SCREEN_WIDTH, 400)];
//    _pickView.pickViewDelegate = self;
//    [_pickView bl_show];
}

///* pickview代理 */
//- (void)bl_selectedAreaResultWithProvince:(NSString *)provinceTitle city:(NSString *)cityTitle area:(NSString *)areaTitle{
//    NSString *areaStr = [NSString stringWithFormat:@"%@-%@-%@",provinceTitle,cityTitle,areaTitle];
//    NSIndexPath *indexPath1 = [NSIndexPath indexPathForRow:2 inSection:0];
//    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath1, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
//    self.AddressLabel.text = areaStr;
//    NSLog(@"%@",areaStr);
//
//}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsMake(0,15,0,15)];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsMake(0,15,0,15)];
    }
}

- (void)saveClick {
    if (self.addressId.length) {
        [self updateUserAddress];
    }
    else {
        [self addUserAddress];
    }
}

- (NSString *)handlePhone:(NSString *)number {
    if (nil == number) {
        return @"";
    }
    if (number.length < 7) {
        return number;
    }
    
    return [number stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
}

- (UITableView *)tableView {
    if (!_tableView) {
        CGRect rect = self.view.frame;
        CGFloat statusH = HFTopStatusHeight;
        CGFloat bottomH = 49;
        if (statusH > 20) {
            bottomH += IPhoneXSafeAreaPotraitBottom;
        }
        rect.size.height -= (HFNavigationHeight + bottomH);
        _tableView = [[UITableView alloc] initWithFrame:rect style:UITableViewStylePlain];
        
        _tableView.delegate     = self;
        _tableView.dataSource   = self;
        _tableView.scrollsToTop = YES;
        
        _tableView.separatorColor = UIColorFromRGB(0xcccccc);
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.tableFooterView = [[UIView alloc] init];
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;
        
        
        if (@available(iOS 11.0, *)){
            self.tableView.estimatedRowHeight = 0;
            self.tableView.estimatedSectionHeaderHeight = 0;
            self.tableView.estimatedSectionFooterHeight = 0;
        }
        
    }
    return _tableView;
}

- (UIButton *)saveBtn {
    if (!_saveBtn) {
        _saveBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [_saveBtn setTitle:@"保存并使用" forState:UIControlStateNormal];
        [_saveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _saveBtn.titleLabel.font = [UIFont systemFontOfSize:18];
        _saveBtn.backgroundColor = UIColorFromRGB(0xFF5101);
        [_saveBtn addTarget:self action:@selector(saveClick) forControlEvents:UIControlEventTouchUpInside];
        
        CGFloat statusH = HFTopStatusHeight;
        CGFloat bottomH = 49;
        if (statusH > 20) {
            bottomH  += IPhoneXSafeAreaPotraitBottom;
        }
        CGFloat screenheight = SCREEN_HEIGHT;
        CGFloat hfnavHeight  = HFNavigationHeight;
        _saveBtn.frame = CGRectMake(0, screenheight-hfnavHeight-bottomH, SCREEN_WIDTH, bottomH);
    }
    
    return _saveBtn;
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0,15,0,15)];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsMake(0,15,0,15)];
    }
}

@end
